package com.fengycx.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fengycx.constants.Constants;
import com.fengycx.pojo.domain.LoginContext;
import com.fengycx.pojo.domain.PayOrder;
import com.fengycx.mapper.PayOrderMapper;
import com.fengycx.service.IPayOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fengycx.templeate.WechatJsapiPayTemplate;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Cino
 * @since 2024-03-20
 */
@Service
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {

    @Autowired
    private WechatJsapiPayTemplate wechatJsapiPayTemplate;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 账单预支付
     * @param orderNo
     * @return
     */
    @Override
    public PrepayWithRequestPaymentResponse payOrderWechatPrepay(String orderNo) {
        //JSR-303 校验
        //业务校验：账单存不存在，账单状态，账单是不是司机本人 TODO
        PayOrder payOrder = super.getOne(new LambdaQueryWrapper<PayOrder>().eq(PayOrder::getOrderNo, orderNo));
        BigDecimal amount = payOrder.getAmount();

        //从redis中拿用户context
        String contextKey = String.format(Constants.Login.LOGIN_CONTEXT_KEY, StpUtil.getLoginIdAsString());
        Object o = redisTemplate.opsForValue().get(contextKey);
        LoginContext loginContext = JSONUtil.toBean(JSONUtil.toJsonStr(o), LoginContext.class);

        return   wechatJsapiPayTemplate.prePay(orderNo,amount.intValue(), loginContext.getOpenId(),"账单");
    }
}
